//
//  MenuVC.m
//  TheProjectName
//
//  Created by 李劲成 on 16/5/19.
//  Copyright © 2016年 sunzhichao. All rights reserved.
//

#import "MenuVC.h"
#import "UserHeadView.h"
#import "WeatherView.h"
#import "WeatherData.h"
@interface MenuVC ()<UITableViewDataSource, UITableViewDelegate, EMContactManagerDelegate, EMChatManagerDelegate, LocalVCDelegate>

@property (nonatomic, retain)UITableView *m_tableView;
/** 标题数组 */
@property (nonatomic, retain) NSArray *itemTitle;
/** 图标数组 */
@property (nonatomic, retain) NSArray *itemImage;
/** 提醒消息视图 (小红点) */
@property (nonatomic, retain) UIView *warnView;

@property (nonatomic, strong) NSArray *viewControllers;

@property (nonatomic, strong) UILocalNotification *notification;

@end

@implementation MenuVC

-(instancetype)init{
    self = [super init];
    if (self) {
        /** 创建4个跳转界面 */
        BaseNaviController *szcVC = [[BaseNaviController alloc] initWithRootViewController:[[SZCViewController alloc] init]];
        BaseNaviController *messageVC = [[BaseNaviController alloc] initWithRootViewController:[[MessageVC alloc] init]];
        BaseNaviController *friendVC = [[BaseNaviController alloc] initWithRootViewController:[[FriendRequestListVC alloc] init]];
        BaseNaviController *skinVC = [[BaseNaviController alloc] initWithRootViewController:[[SkinVC alloc] init]];
        self.viewControllers = @[szcVC, messageVC, friendVC, skinVC];
        
        /** 在控制器创建的时候 创建提醒视图 */
        self.warnView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 10, 10)];
        _warnView.layer.cornerRadius = 5;
        _warnView.backgroundColor = [UIColor redColor];
        // 判断本地是否含有未处理好友申请的文件
        if (![[LocalCache sharedLocalCache]diskfileExistsWithKey:[EMClient sharedClient].currentUsername]) {
            // 隐藏
            _warnView.hidden = YES;
        }
        // 异步添加监听好友申请
        [[EMClient sharedClient].contactManager addDelegate:self delegateQueue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)];
        // 异步添加接收消息
        [[EMClient sharedClient].chatManager addDelegate:self delegateQueue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)];
    }
    return self;
}

#pragma mark - 监听好友 申请回调
- (void)didReceiveFriendInvitationFromUsername:(NSString *)aUsername
                                       message:(NSString *)aMessage{
//    // 显示提醒视图
//    [UIView animateWithDuration:0.1 animations:^{
//        _warnView.hidden = NO;
//    }];
    
   

    // 判断本地是否含有文件以此来判断是否为仅有的好友申请
    if (![[LocalCache sharedLocalCache]diskfileExistsWithKey:[EMClient sharedClient].currentUsername])  {
        // 创建数组添加用户名
        NSArray *arr = [NSArray arrayWithObject:aUsername];
        // 数组写入本地
        [[LocalCache sharedLocalCache]storeArray:arr toDiskforKey:[EMClient sharedClient].currentUsername];
    }
    else{
        // 获取之前的好友申请
        NSArray *array = [[LocalCache sharedLocalCache]readArrayFromDiskWithKey:[EMClient sharedClient].currentUsername];
        NSMutableArray *m_arr = [NSMutableArray arrayWithArray:array];
        // 添加
        [m_arr addObject:aUsername];
        // 数组写入本地
        [[LocalCache sharedLocalCache]storeArray:m_arr toDiskforKey:[EMClient sharedClient].currentUsername];
    }
          // 通知接收到消息
    [[NSNotificationCenter defaultCenter]postNotificationName:@"receive" object:nil];
}

#pragma mark - 接收消息回调
- (void)didReceiveMessages:(NSArray *)aMessages{
    
    [[NSNotificationCenter defaultCenter]postNotificationName:@"message" object:nil];dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
      
        //本地推送
        if (!_notification) {
           self.notification = [[UILocalNotification alloc]init];
            _notification.soundName = UILocalNotificationDefaultSoundName;
            _notification.alertBody = @"您有新的未读消息";
            NSDictionary*info = [NSDictionary dictionaryWithObject:@"test" forKey:@"name"];
            _notification.userInfo = info;
            _notification.timeZone = [NSTimeZone defaultTimeZone];
            _notification.repeatInterval = kCFCalendarUnitDay;
        }

        NSDate * pushDate = [NSDate dateWithTimeIntervalSinceNow:10];
        if (_notification != nil) {
            _notification.fireDate = pushDate;
      
            NSArray *conversations = [[EMClient sharedClient].chatManager getAllConversations];
            NSInteger unreadCount = 0;
            for (EMConversation *conversation in conversations) {
                unreadCount += conversation.unreadMessagesCount;
            }
              _notification.applicationIconBadgeNumber = unreadCount;
            
        }
        //添加推送到UIApplication
        UIApplication *app = [UIApplication sharedApplication];
        [app scheduleLocalNotification:_notification];
    });
}



- (void)viewDidLoad {
    [super viewDidLoad];
    self.itemTitle = @[@"每日必跑", @"会话列表",@"好友请求", @"一键换肤"];
    self.itemImage = @[@"IconHome", @"IconCalendar",@"IconProfile", @"IconSettings"];
    self.locker.delegate = self;
    [self createSubViews];

    // Do any additional setup after loading the view.
}

- (void)locker:(LockerVC *)locker willShowMenuViewController:(UIViewController *)menuViewController{
    if (![[LocalCache sharedLocalCache]diskfileExistsWithKey:[EMClient sharedClient].currentUsername])  {
        _warnView.hidden = YES;
    }
    else{
        _warnView.hidden = NO;
    }
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - 创建子视图
- (void)createSubViews {
    
    self.m_tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT * 0.15, FRAME_WIDTH(self.view) / 1.65, SCREEN_HEIGHT * 0.8) style:UITableViewStylePlain];
    _m_tableView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth;
    _m_tableView.delegate = self;
    _m_tableView.dataSource = self;
    _m_tableView.opaque = NO;
    _m_tableView.backgroundColor = [UIColor clearColor];
    _m_tableView.backgroundView = nil;
    _m_tableView.rowHeight = SCREEN_HEIGHT * 0.08;
    _m_tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _m_tableView.bounces = NO;
    _m_tableView.tableHeaderView = [[UserHeadView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH - 150, SCREEN_HEIGHT * 0.24) addTarget:self action:@selector(pushUserDetail)];
    _m_tableView.tableFooterView =[[WeatherView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH - 150, SCREEN_HEIGHT * 0.24)];;
    [self.view addSubview:_m_tableView];
    
    
    
}

#pragma mark - 推出用户详情页
- (void)pushUserDetail{
    [self.locker setContentViewController:[[BaseNaviController alloc] initWithRootViewController:[[UserDetailVC alloc] init]]
                                                 animated:YES];
    [self.locker hideMenuViewController];
    
}

#pragma mark -
#pragma mark UITableView Delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    // 推出界面
    [self.locker setContentViewController:_viewControllers[indexPath.item]];
    [self.locker hideMenuViewController];

}

#pragma mark -
#pragma mark UITableView Datasource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)sectionIndex
{
    return _itemTitle.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        cell.backgroundColor = [UIColor clearColor];
        cell.textLabel.font = [UIFont fontWithName:@"HelveticaNeue" size:20];
        cell.textLabel.textColor = [UIColor whiteColor];
        cell.textLabel.highlightedTextColor = [UIColor lightGrayColor];
        cell.selectedBackgroundView = [[UIView alloc] init];
    }
    if (indexPath.row == 2) {
        cell.accessoryView = _warnView;
    }
    
    cell.textLabel.text = _itemTitle[indexPath.row];
    cell.imageView.image = [UIImage imageNamed:_itemImage[indexPath.row]];
    return cell;
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
